//
//  WeekViewController.swift
//  YOKO
//
//  Created by 鲁浩 on 16/5/6.
//  Copyright © 2016年 15Tec. All rights reserved.
//

import UIKit

protocol WeekViewControllerDelegate {
	func backToDayViewController()
	func WeekViewbackToMonthViewController()
}

class WeekViewController: UIViewController {

	let cellHeight: CGFloat = 56.0
	let topViewLineHeight: CGFloat = 18.0

	var topViewsLineNum = 0
	var topEvents = [EventInWeekView]()
	var events = [[EventInWeekView]]()

	var delegate: WeekViewControllerDelegate? = nil

	var weekOverTitleView: WeekOverTitleView!

	var dayViewButton: UIButton!

	@IBOutlet weak var titleView: UIView!
    
    var contentView: WeekView!

	var weekDateViews = [DateWithLunaView]()

	var date: NSDate? {
		didSet {
			self.initDateTitleViews()
            readAllEvents()
            initContentView()
		}
	}

	@IBOutlet weak var weekScrollView: UIScrollView!
    
    func readAllEvents() {
        let totalEvents = uiRealm.objects(Event).filter("timeBegin < %@ AND timeEnd > %@ AND calendarId = %@",
            NSDate.lastPlus1DayOfWeek(self.date!), NSDate.firstDayOfWeek(self.date!),
            NSUserDefaults.getCurrentCalendarId()).sorted("timeBegin")
        
        var weekHeadEvents = Array<Array<Int>>()
//        weekHeadEvents.append(Array<Int>(count: 7, repeatedValue: 0))
        let firstDayOfWeek = NSDate.firstDayOfWeek(self.date!)
        let dayOfWeekBegin = NSDate.day(firstDayOfWeek)
        let lastDayOfWeek = NSDate.lastDayOfWeek(self.date!)
        
        topEvents.removeAll()
        events.removeAll()
        
        // 插入全天或跨天事件
        for e in totalEvents {
            if (e.getEventType() <= 1) {
                if (weekHeadEvents.isEmpty) {
                    weekHeadEvents.append(Array<Int>(count: 7, repeatedValue: 0))
                }
                var timeBegin = e.timeBegin
                var timeEnd = e.timeEnd
                if (e.timeBegin < firstDayOfWeek) {
                    timeBegin = firstDayOfWeek
                }
                if (e.timeEnd > lastDayOfWeek) {
                    timeEnd = lastDayOfWeek
                }
                var dayOfTimeBegin = NSDate.day(timeBegin)
                var dayOfTimeEnd = NSDate.day(timeEnd)
                if (dayOfTimeBegin < dayOfWeekBegin) {
                    dayOfTimeBegin = dayOfTimeBegin + NSDate.totalDaysInTheMonth(firstDayOfWeek)
                }
                if (dayOfTimeEnd < dayOfWeekBegin) {
                    dayOfTimeEnd = dayOfTimeEnd + NSDate.totalDaysInTheMonth(firstDayOfWeek)
                }
                var flag = true
                var startY = 0
                for i in 0..<weekHeadEvents.count {
                    var counter = 0
                    for j in (dayOfTimeBegin - dayOfWeekBegin) ... (dayOfTimeEnd - dayOfWeekBegin) {
                        if (weekHeadEvents[i][j] == 0) {
                            counter = counter + 1
                        }
                    }
                    if (counter == (dayOfTimeEnd - dayOfTimeBegin + 1)) {
                        startY = i
                        flag = false
                        for j in (dayOfTimeBegin - dayOfWeekBegin) ... (dayOfTimeEnd - dayOfWeekBegin) {
                            weekHeadEvents[startY][j] = 1
                        }
                        break
                    }
                }
                if (flag) {
                    startY = weekHeadEvents.count
                    weekHeadEvents.append(Array<Int>(count: 7, repeatedValue: 0))
                }
                for i in (dayOfTimeBegin - dayOfWeekBegin) ... (dayOfTimeEnd - dayOfWeekBegin) {
                    weekHeadEvents[startY][i] = 1
                }
                let topEvent = EventInWeekView()
                topEvent.colorType = e.type
                topEvent.dateWidth = dayOfTimeEnd - dayOfTimeBegin + 1
                topEvent.startY = startY
                topEvent.startX = dayOfTimeBegin - dayOfWeekBegin
                topEvent.title = e.summary
                topEvents.append(topEvent)
            }
        }
        
        for m in 0 ... 6 {
            var singleDayEventList = [EventInWeekView]()
            
            let day = NSDate.theNextDays(firstDayOfWeek, day: m)
            let dayBegin = NSDate.beginOfDay(day)
            let dayEnd = NSDate.endOfDay(day)
            let dayEvents = totalEvents.filter("timeBegin < %@ AND timeEnd > %@ ", dayEnd, dayBegin).sorted("timeBegin")
            
            // 插入非全天或跨天事件
            var singleDay = Array<Array<Int>>()
            for _ in 0...3 {
                let singleDayPiece = Array<Int>(count: 96, repeatedValue: 0)
                singleDay.append(singleDayPiece)
            }
            for e in dayEvents {
                if (e.getEventType() > 1) {
                    let sectionOfTimeBegin = (e.timeBegin.minute + 60 * e.timeBegin.hour) / 15
                    let sectionOfTimeEnd = (e.timeEnd.minute + 60 * e.timeEnd.hour) / 15
                    var flag = true
                    var starX = 0
                    for i in 0...3 {
                        var counter = 0
                        for j in sectionOfTimeBegin...sectionOfTimeEnd {
                            if (singleDay[i][j] == 0) {
                                counter = counter + 1
                            }
                        }
                        if (counter == (sectionOfTimeEnd - sectionOfTimeBegin + 1)) {
                            flag = false
                            starX = i
                            for j in sectionOfTimeBegin...sectionOfTimeEnd {
                                singleDay[starX][j] = 1
                            }
                            break
                        }
                    }
                    if (flag) {
                        starX = 4
                    }
                    let event = EventInWeekView()
                    event.colorType = e.type
                    event.startX = starX
                    event.startY = sectionOfTimeBegin
                    event.timeHeight = sectionOfTimeEnd - sectionOfTimeBegin
                    if (event.timeHeight == 0) {
                        event.timeHeight = 1
                    }
                    event.title = e.summary
                    singleDayEventList.append(event)
                }
            }
            
            events.append(singleDayEventList)
        }
        topViewsLineNum = weekHeadEvents.count
        
    }

	override func viewDidLoad() {
		super.viewDidLoad()

		titleView.layer.shadowOffset = CGSizeMake(0, 2)
		titleView.layer.shadowColor = UIColor.lightGrayColor().CGColor
		titleView.layer.shadowRadius = 3
		titleView.layer.shadowOpacity = 0.4
        
        readAllEvents()
        
		self.initsubView()
		// Do any additional setup after loading the view.
	}
    
    func initContentView() {
        
        if contentView != nil {
            contentView.removeFromSuperview()
        }
        contentView = WeekView()
        contentView.backgroundColor = UIColor.clearColor()
        contentView.frame = CGRectMake(0, 0, screenWidth, cellHeight * 24 + CGFloat(topViewsLineNum) * topViewLineHeight)
        contentView.topViewLineNum = topViewsLineNum
        contentView.events = events
        contentView.topEvents = topEvents
        
        self.weekScrollView.bounces = false
        self.weekScrollView.contentInset = UIEdgeInsetsZero
        self.weekScrollView.showsHorizontalScrollIndicator = false
        self.weekScrollView.addSubview(contentView)
        self.weekScrollView.contentSize.height = contentView.bounds.size.height
        
    }

    //ViewDidLoad 时调用
	func initsubView() {
        
        initContentView()

		weekOverTitleView = NSBundle.mainBundle().loadNibNamed("WeekOverTitleView", owner: self, options: nil).last as? WeekOverTitleView

		weekOverTitleView!.frame = CGRectMake(0, 0, screenWidth, 24)
		self.view.addSubview(weekOverTitleView!)

	}

	func initDateTitleViews() {

		for view in weekDateViews {
			view.removeFromSuperview()
		}

		weekDateViews.removeAll()

		// 计算当前时间所在周的第一天
		let firstDay = NSDate.firstDayOfWeek(self.date!)
		let components = NSDateComponents()

		for i in 0 ... 6 {
			let dateView = NSBundle.mainBundle().loadNibNamed("DateWithLunaView", owner: self, options: nil).last as? DateWithLunaView
			components.day = i
			let date = NSCalendar.currentCalendar().dateByAddingComponents(components, toDate: firstDay, options: .MatchStrictly)
			dateView?.date = date
			self.view.addSubview(dateView!)

			dateView?.frame = CGRectMake((screenWidth / 7) * CGFloat(i), 24.0, screenWidth / 7, 30.0)
			weekDateViews.append(dateView!)
		}
        
	}

	@IBAction func backToDayView() {
		self.delegate?.backToDayViewController()
	}

	@IBAction func backToMonthView() {
		self.delegate?.WeekViewbackToMonthViewController()
	}

	override func didReceiveMemoryWarning() {
		super.didReceiveMemoryWarning()
		// Dispose of any resources that can be recreated.
	}

}
